package com.ccsc.auth.controller;

import com.ccsc.auth.SystemException.IpCheckFailException;
import com.ccsc.auth.entity.*;
import com.ccsc.auth.entity.vi.UserVi;
import com.ccsc.auth.entity.vo.*;
import com.ccsc.auth.service.*;
import com.ccsc.auth.utils.BaseResponse;
import com.ccsc.auth.utils.DataMap;
import com.ccsc.auth.utils.IpUtil;
import com.ccsc.auth.utils.Page;
import com.google.common.collect.Lists;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by yyangs on 2017/2/17.
 */
@RestController
@RequestMapping("/SysUserManage")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService sysUserService;


    //获取全部用户信息通过列表分页
    @RequestMapping(value = "/usersBypages", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllUserBypages(WebRequest request,
                                          @RequestParam(required =false,defaultValue ="1")int page,
                                          @RequestParam(required =false,defaultValue ="5")int pageSize) throws Exception {
        DataMap params = getParam(request);
        params.put("page", page);
        params.put("pageSize", pageSize);
        try {
            Page pageList = sysUserService.getUsersByPage(params);
            List<SysUser> userList = pageList.getContent();
            List<SysUserVo> userVoList = Lists.newArrayList();
            if(userList!=null && userList.size() > 0){
                for(SysUser user : userList){
                    SysUserVo sysUserVo = new SysUserVo();
                    BeanUtils.copyProperties(sysUserVo, user);
                    sysUserVo.setPhone(user.getTel());
                    sysUserVo.setMail(user.getEmail());
                    sysUserVo.setAuth(String.valueOf(user.getType()));
                    if (9 == user.getType()){
                        sysUserVo.setAuth("1,2");
                    }
                    sysUserVo.setDeleteable(1);
                    if ("superAdmin".equals(user.getAccount())){
                        sysUserVo.setDeleteable(0);
                    }
                    sysUserVo.setStatus(user.getStatus());
                    sysUserVo.setNote(user.getRemark());
                    userVoList.add(sysUserVo);
                }
            }
            pageList.setContent(userVoList);
            return this.ok(pageList);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //添加新用户
    @RequestMapping(value = "/addSysUser", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse addUser(@RequestBody SysUserVo sysUserVo) throws Exception {
        try {
            Integer result=0;
            //User user=userVi2User(userVi);
            //判断账号是否重复
            List<SysUser> users=sysUserService.getUsersByAccount(sysUserVo.getAccount());
            if(users.size()>0){
                return this.error(500,"用户账号已存在，请修改");
            }

            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUser, sysUserVo);
            sysUser.setTel(sysUserVo.getPhone());
            sysUser.setEmail(sysUserVo.getMail());
            if (sysUserVo.getAuth().contains(",")){
                sysUser.setType(9);
            }else{
                sysUser.setType(Integer.parseInt(sysUserVo.getAuth()));
            }
            sysUser.setStatus(sysUserVo.getStatus());
            sysUser.setRemark(sysUserVo.getNote());

            result = sysUserService.createUser(sysUser);

            return this.ok(result);
        }catch (IpCheckFailException e){
            ResponseData responseData = new ResponseData();
            responseData.setId(e.getId());
            responseData.setMessage(e.getMessage());
            List<ResponseData> responseDatas = Lists.newArrayList();
            responseDatas.add(responseData);
            return new BaseResponse(900,responseDatas);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //修改用户
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse updateUser(@RequestBody SysUserVo sysUserVo) throws Exception {
        try {
            Integer result=0;
            SysUser userTemp=sysUserService.getUserById(sysUserVo.getId());
            if(userTemp == null) {
                return this.error(500, "该用户不存在！");
            }

            if(userTemp.getPassword().equals(sysUserVo.getPassword())){
                sysUserVo.setPassword(null);
            }
            //判断账号是否重复
            List<SysUser> users=sysUserService.getUsersByAccount(userTemp.getAccount());
            if((users.size()==1&&!users.get(0).getId().equals(userTemp.getId()))||users.size()>1){
                return this.error(500,"用户账号名称已存在，修改失败");
            }

            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUser, sysUserVo);
            sysUser.setTel(sysUserVo.getPhone());
            sysUser.setEmail(sysUserVo.getMail());
            if (sysUserVo.getAuth().contains(",")){
                sysUser.setType(9);
            }else{
                sysUser.setType(Integer.parseInt(sysUserVo.getAuth()));
            }
            sysUser.setStatus(sysUserVo.getStatus());
            sysUser.setRemark(sysUserVo.getNote());

            result = sysUserService.updateUser(sysUser);

            return this.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //删除用户
    @RequestMapping(value = "/delUser/{userId}", method = RequestMethod.DELETE, produces = {"application/json", "application/xml"})
    public BaseResponse deleteUser(@PathVariable("userId")String userIdIn) throws Exception {
        Integer userId=Integer.parseInt(userIdIn);
        try {
            Integer result=0;
            SysUser user = sysUserService.getUserById(userId);
            if(user!=null) {
                result= sysUserService.deleteUserById(userId);
            }
            return this.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

//    //批量删除用户
//    @RequestMapping(value = "/deleteUsers", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
//    public BaseResponse deleteUsers(WebRequest request) throws Exception {
//        DataMap params = getParam(request);
//        String ids=(String) params.get("ids");
//        try {
//            Integer result=0;
//            String[] strings=ids.split(",");
//            for(int i=0;i<strings.length;i++){
//                Integer userId=Integer.parseInt(strings[i]);
//                SysUser user = sysUserService.getUserById(userId);
//                if(user!=null) {
//                    result= sysUserService.deleteUserById(userId);
//                }
//            }
//            return this.ok(result);
//        }catch (Exception e){
//            e.printStackTrace();
//            return this.error(500, e.getMessage());
//        }
//    }

    public static User SysUser2User(SysUser sysUser) throws Exception{
        User user = new User();
        user.setAccount(sysUser.getAccount());
        user.setName(sysUser.getName());
        user.setPassword(sysUser.getPassword());
        user.setSex(1);
        user.setMail(sysUser.getEmail());
        user.setPhone(sysUser.getTel());
        user.setStatus(1);
        user.setSysuserid(sysUser.getId());
        //添加默认角色与职位
        Department department=new Department();
        department.setId(1);
        Position position=new Position();
        position.setId(2);
        position.setDepartment(department);
        Map<Department,Position> departmentPositionMap=new ManagedMap<>();
        departmentPositionMap.put(department,position);
        List<Map<Department,Position>> mapList=new ArrayList<>();
        mapList.add(departmentPositionMap);
        user.setPositionMap(mapList);
        List<Role> roleList=new ArrayList<>();
        Role role = new Role();
        role.setId(9);
        roleList.add(role);
        user.setRoleList(roleList);
        user.setVerify_type(0);

        return user;
    }

}
